﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Liang.Util.Config
{
    /// <summary>
    /// 配置文件
    /// </summary>
    public class InitFile
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strFile"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SerializeData<T>(string strFile, object obj)
        {
            try
            {
                Stream fStream = new FileStream(strFile, FileMode.Create, FileAccess.Write);
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
                xmlFormat.Serialize(fStream, obj);
                fStream.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 反序列化数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strFile"></param>
        /// <returns></returns>
        public static object DeSerializeData<T>(string strFile)
        {
            object obj = null;

            try
            {
                Stream fStream = new FileStream(strFile, FileMode.Open, FileAccess.Read);
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
                obj = xmlFormat.Deserialize(fStream);
                fStream.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return obj;
        }
    }
}
